package com.lst.tools.basics.utils;


import com.lst.tools.basics.exception.ValidatorException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * @author: Frank
 * @date: 2019/09/24 13:51
 * @version: V1.0
 */
public class ValidatorUtils {

    private static Validator validator;

    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    public static <T> void validate(T t) throws ValidatorException {
        //验证实体类里面的字段，把不符合条件的字段的内容存到Set集合里面，再遍历拼接错误信息
        Set<ConstraintViolation<T>> set = validator.validate(t);
        if (set.size() > 0) {
            StringBuilder sb = new StringBuilder();
            int i = 0;
            for (ConstraintViolation<T> cv : set) {
                sb.append(cv.getPropertyPath().toString());
                sb.append(":");
                sb.append(cv.getMessage());
                if (i != set.size() - 1) {
                    sb.append(" | ");
                }
                i++;
            }
            throw new ValidatorException(sb.toString());
        }
    }


}
